package com.wenda.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wenda.admin.bean.Account;
import com.wenda.admin.constant.UserTypeEnum;
import com.wenda.admin.mapper.AccountMapper;
import com.wenda.admin.mapper.SecurityPersonnelMapper;
import com.wenda.admin.mapper.StudentMapper;
import com.wenda.admin.mapper.TeacherMapper;
import com.wenda.admin.vo.LoginVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LoginController {
    private final AccountMapper accountMapper;
    private final StudentMapper studentMapper;
    private final TeacherMapper teacherMapper;
    private final SecurityPersonnelMapper securityMapper;


    @RequestMapping("login")
    public String loginIndex(Model model){
        return "login";
    }

    @RequestMapping("loginForm")
    public String login(String userName, String password, Model model, HttpSession session){
        if(StringUtils.isBlank(userName) || StringUtils.isBlank(password)){
            model.addAttribute("msg","用户名或者密码不能为空");
            return loginIndex(model);
        }
        Account account = accountMapper.selectOne(new LambdaQueryWrapper<Account>().eq(Account::getMobile,userName).eq(Account::getPasssword,password));
        if(account == null){
            model.addAttribute("msg","用户名或者密码错误");
            return loginIndex(model);
        }

        LoginVO loginVO = new LoginVO();
        loginVO.setAccountId(account.getId());
        loginVO.setInfoId(account.getInfoId());
        loginVO.setName(account.getName());
        loginVO.setMobile(account.getMobile());
        loginVO.setCode(account.getCode());
        loginVO.setUserType(account.getUserType());
        session.setAttribute("userKey",loginVO);
        model.addAttribute("userKey",loginVO);

        UserTypeEnum userType = UserTypeEnum.toEnum(account.getUserType());
        switch (userType){
            case STUDENT:
                loginVO.setStudentInfo(studentMapper.selectById(account.getInfoId()));
                return "/code/index";
            case TEACHER:
                loginVO.setTeacherInfo(teacherMapper.selectById(account.getInfoId()));
                return "/code/index";
            case SECURITY:
                loginVO.setSecurityInfo(securityMapper.selectById(account.getInfoId()));
                return "/scan/index";
        }

        return "/index";
    }

    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.invalidate();
        return loginIndex(null);
    }
}
